package de.hhbk.feedbackmodul.daobeans;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import de.hhbk.feedbackmodul.daointerfaces.ParticipantDaoIF;
import de.hhbk.feedbackmodul.entities.Participant;

@Stateless
public class ParticipantDaoBean implements ParticipantDaoIF {

	@PersistenceContext(unitName = "FeedbackModulEJB")
	private EntityManager manager;
	
	private Logger logger = Logger.getLogger(this.getClass());
	

	@SuppressWarnings("unchecked")
	@Override
	public List<Participant> getAllParticipants() throws Exception  {
		try
		{
			Query query = manager.createQuery("select p from Participant p", Participant.class);
			return (List<Participant>) query.getResultList();
		}
		catch(Exception e)
		{
			logger.error("Error while reading Participants: "+e.getMessage(), e);
			throw e;
		}
	}


	@Override
	public void createParticipant(Participant participant) throws Exception {
		try
		{
			manager.persist(participant);
		}
		catch(Exception e)
		{
			logger.error("Error while persisting Participant: "+e.getMessage(), e);
			throw e;
		}
	}


	@Override
	public void updateParticipant(Participant participant) throws Exception {
		try
		{
			manager.merge(participant);
		}
		catch(Exception e)
		{
			logger.error("Error while updating Participant: "+e.getMessage(), e);
			throw e;
		}
	}


	@Override
	public void deleteParticipant(Participant participant) throws Exception {
		try
		{
			Participant participantToDelete = manager.find(Participant.class, participant.getId());
			manager.remove(participantToDelete);
		}
		catch(Exception e)
		{
			logger.error("Error while deleting Participant: "+e.getMessage(), e);
			throw e;
		}
	}

}
